#include "mesh_timer.h"
#include "mesh_coordinator_std.h"


void
ActiveNeighborTimer::handle(Event*) {
 
//	mac_->bwmanager ()->
	std::map<W_MeshNodeId, MeshCoordinatorStandard::NeighInfo*> & Dsch_ = mac_->coordinator()->nghMapDsch() ;
	std::map<W_MeshNodeId, MeshCoordinatorStandard::NeighInfo*> & Ncfg_ = mac_->coordinator()->nghMapNcfg() ;

	std::map<W_MeshNodeId, unsigned int> timeoutNode_;

	std::list<MeshCoordinatorStandard::NeighInfo>::iterator it;


	for ( it = mac_->coordinator()->nghListDsch().begin() ; it !=mac_->coordinator()->nghListDsch().end() ; ++it) {
		W_MeshNodeId NodeId_ = it->nodeID_;
		
		double lastTime_ = 0 ;

//		double ind1_ = Dsch_[NodeId_]->timeSec_;
//		double ind2_ = Ncfg_[NodeId_]->timeSec_;

//		unsigned int ind3_ = Dsch_[NodeId_]->timeStamp_;
//		double ind4_ = mac_->coordinator()->nghMapDsch_[NodeId_]->timeSec_;

//		MeshCoordinatorStandard::NeighInfo* ind5_ = it->second;
//		MeshCoordinatorStandard::NeighInfo* ind6_ = Ncfg1[NodeId_];
/*
		double ds = Dsch_[NodeId_]->timeSec_;
		double nc = Ncfg_[NodeId_]->timeSec_;

		if ( ds > nc ) {
			lastTime_ = ds;
		} else {
			lastTime_ = nc;
		}
*/
		double n4 = it->timeSec_;
		int    n5 = mac_->coordinator()->nghListDsch().size();
		double n1 = CURRENT_TIME - lastTime_;
		double n2 = Dsch_[NodeId_]->timeSec_;
		double n3 = Ncfg_[NodeId_]->timeSec_;
		
		
		
		( (Dsch_[NodeId_]->timeSec_) > (Ncfg_[NodeId_]->timeSec_) ) ? lastTime_ = Dsch_[NodeId_]->timeSec_ : lastTime_ = Ncfg_[NodeId_]->timeSec_ ;
		// 只在dsch中判断是否为一跳，有待完善；


		

		if ( (CURRENT_TIME - lastTime_) > 1.0 ) {
			// 表示节点超时了，记录下超时的节点；
			timeoutNode_[ NodeId_ ] = it->nhop_;
		}
	}

	std::map<W_MeshNodeId,unsigned int>::iterator pt;

	for (pt = timeoutNode_.begin(); pt != timeoutNode_.end(); ++pt) {

		W_MeshNodeId NodeId_ = pt->first ;
		//unsigned int ndx = mac_->neigh2ndx( NodeId_);
		


	//删除coor中的邻居信息;

		mac_->coordinator()->nghMapDsch().erase (NodeId_);
		mac_->coordinator()->nghMapNcfg().erase (NodeId_);
		
		std::list<MeshCoordinatorStandard::NeighInfo>::iterator it;
		for (it=mac_->coordinator()->nghListNcfg().begin();it!= mac_->coordinator()->nghListNcfg().end();++it) {
			if ( it->nodeID_ == NodeId_ ) { 
				mac_->coordinator()->nghListNcfg().erase (it);
				// 防止迭代器失效
				it = mac_->coordinator()->nghListNcfg().begin();
			}
		}
		
		for (it = mac_->coordinator()->nghListDsch().begin();it != mac_->coordinator()->nghListDsch().end(); ++it ) {
			if ( it->nodeID_ == NodeId_ ) { 
				mac_->coordinator()->nghListDsch().erase (it);
				it = mac_->coordinator()->nghListDsch().begin();
			}
		}
		

	//删除coor中的邻居信息;
		if ( pt->second == 1 ) {
	
			mac_->coordinator()->deleteNode ( NodeId_ );
		}
	}

	double interval = 1.0;
	assert(interval >= 0);

//	mac_->scheduler()->link_.swap( mac_->scheduler()->link_.swap );

	printf( "检测了一次邻居是否超时 %f\n" , NOW );
	Scheduler::instance().schedule(this, &intr, interval);
}





